<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>{{ isRegister ? '用户注册' : '用户登录' }}</h2>
        <p>{{ isRegister ? '创建您的账号' : '欢迎回来' }}</p>
      </div>

      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        class="login-form"
        @submit.prevent="handleSubmit"
      >
        <el-form-item prop="username" v-if="isRegister">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item prop="loginName" v-if="!isRegister">
          <el-input
            v-model="formData.loginName"
            placeholder="请输入用户名或邮箱"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>

        <el-form-item prop="email" v-if="isRegister">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
            size="large"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword" v-if="isRegister">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item v-if="!isRegister">
          <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            :loading="loading"
            @click="handleSubmit"
          >
            {{ isRegister ? '注册' : '登录' }}
          </el-button>
        </el-form-item>

        <div class="login-footer">
          <el-button
            type="text"
            @click="toggleMode"
            class="toggle-btn"
          >
            {{ isRegister ? '已有账号？立即登录' : '没有账号？立即注册' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { register } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const isRegister = ref(false)
const loading = ref(false)
const formRef = ref()

const formData = reactive({
  username: '',
  loginName: '',
  email: '',
  password: '',
  confirmPassword: '',
  rememberMe: false
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== formData.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  loginName: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

const toggleMode = () => {
  isRegister.value = !isRegister.value
  resetForm()
}

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'rememberMe') {
      formData[key] = false
    } else {
      formData[key] = ''
    }
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isRegister.value) {
      await handleRegister()
    } else {
      await handleLogin()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

const handleRegister = async () => {
  try {
    const result = await register({
      username: formData.username,
      email: formData.email,
      password: formData.password,
      confirmPassword: formData.confirmPassword
    })

    if (result.success) {
      ElMessage.success(result.message || '注册成功')
      isRegister.value = false
      resetForm()
    } else {
      ElMessage.error(result.message || '注册失败')
    }
  } catch (error) {
    ElMessage.error('注册失败，请稍后重试')
  }
}

const handleLogin = async () => {
  try {
    const result = await userStore.userLogin({
      loginName: formData.loginName,
      password: formData.password,
      rememberMe: formData.rememberMe
    })

    if (result.success) {
      ElMessage.success(result.message || '登录成功')

      if (userStore.isAdmin()) {
        router.push('/blogmanagement')
      } else {
        router.push('/blogview')
      }
    } else {
      ElMessage.error(result.message || '登录失败')
    }
  } catch (error) {
    ElMessage.error('登录失败，请稍后重试')
  }
}
</script>

<style>
/* 全局重置样式 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

#app {
  height: 100vh;
  width: 100vw;
}
</style>

<style scoped>
:root {
  --macaron-pink: #ffcfd2;
  --macaron-mint: #b4fae4;
  --macaron-blue: #a3c4f3;
  --macaron-purple: #cdb4db;
  --macaron-yellow: #fde4cf;
  --macaron-grey: #f8f9fa;
  --macaron-white: #ffffff;
  --macaron-dark: #495057;
}

.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, var(--macaron-purple), var(--macaron-mint), var(--macaron-pink), var(--macaron-blue));
  padding: 20px;
  margin: 0;
  overflow: hidden;
}

.login-card {
  background: var(--macaron-white);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  padding: 40px;
  width: 100%;
  max-width: 420px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: var(--macaron-dark);
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.login-header p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  border-radius: 8px;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, var(--macaron-purple), var(--macaron-blue));
  border: none;
  transition: all 0.3s ease;
  color: white;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(163, 196, 243, 0.4);
  background: linear-gradient(135deg, var(--macaron-blue), var(--macaron-purple));
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.toggle-btn {
  color: var(--macaron-purple);
  font-size: 14px;
  padding: 0;
}

.toggle-btn:hover {
  color: var(--macaron-blue);
}

@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
    margin: 10px;
  }

  .login-header h2 {
    font-size: 24px;
  }
}
</style>